from socket import socket, SOCK_STREAM,\
    AF_INET, SOCK_DGRAM
import numpy as np
from tools.log import log
import multiprocessing as mp

class WifiConfig():
    def __init__(self):
        try:
            s = socket(AF_INET, SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
            print("ip:", ip)
        finally:
            s.close()

        tmp = ip.split('.')
        carip = '.'.join(tmp[:-1] + ['', ]) + str(254)
        self.server_adder = (carip, 60000)
        log.info(self.server_adder)

        # AF_INET表示IPV4地址，SOCK_STREAM表示走TCP
        self.client = socket(AF_INET, SOCK_STREAM)

        # 建立连接
        self.client.connect(self.server_adder)

    def _checkData(self, pack_length=12):
        while True:
            dat_buf = self.client.recv(pack_length)
            if len(dat_buf) == 12 and dat_buf[0] == 0x55:
                break
            else:
                print('skip error package')
        return dat_buf

    def datRead(self, flag=True):
        wifi_msg = self._checkData()
        if flag:
            print(wifi_msg)
            print("运行状态：{}".format(wifi_msg[2]))
            print("光敏状态：{}".format(wifi_msg[3]))
            print("距离:{}mm".format((wifi_msg[5] << 8) + wifi_msg[4]))
            print("光照：{}lx".format((wifi_msg[7] << 8) + wifi_msg[6]))
            print("码盘：{}".format((wifi_msg[9] << 8) + wifi_msg[8]))
        return wifi_msg

    def send(self, send_dat):
        self.client.send(send_dat)

    def datSeed(self, comm0, comm1, comm2, comm3, comm4):
        send_dat = np.zeros((8,), np.uint8)
        send_dat[0] = 0x55
        send_dat[1] = comm0
        send_dat[2] = comm1
        send_dat[3] = comm2
        send_dat[4] = comm3
        send_dat[5] = comm4
        send_dat[6] = (send_dat[2] + send_dat[3] + send_dat[4] + send_dat[5]) % 256
        send_dat[7] = 0xBB
        self.client.send(send_dat)

if __name__ == "__main__":
    wifi = WifiConfig()